package org.example.admin.flight;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

/**
 * 航班不完成删除功能,因为有外键!!!
 */
public class deleteFlightView extends JFrame {
    private JTextField flightIdField;
    private JButton deleteButton;

    public deleteFlightView() {
        setTitle("管理端航班删除信息页面");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridLayout(4, 2));

        JLabel flightIdLabel = new JLabel("ID");
        flightIdField = new JTextField();
        deleteButton = new JButton("删除");

        // 添加组件到窗口
        add(flightIdLabel);
        add(flightIdField);

        add(new JLabel()); // 占位
        add(deleteButton);

        // 添加删除按钮的点击事件监听器
        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                deleteData();
            }
        });
    }

    private void deleteData() {
        int id = Integer.parseInt(flightIdField.getText());

        try {
            // 连接数据库
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:Mysql://localhost:3306/airlines", "username", "password");

            // 创建删除语句
            String deleteQuery = "DELETE FROM air_flight WHERE flight_id = ?";
            PreparedStatement statement = conn.prepareStatement(deleteQuery);
            statement.setInt(1, id);

            // 执行删除操作
            int rowsDeleted = statement.executeUpdate();

            // 关闭连接和语句
            statement.close();
            conn.close();

            if (rowsDeleted > 0) {
                JOptionPane.showMessageDialog(this, "数据删除成功");
            } else {
                JOptionPane.showMessageDialog(this, "数据不存在或删除失败");
            }

            // 清空输入框
            flightIdField.setText("");

        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "删除数据失败：" + e.getMessage());
        }
    }

    public static void main(String[] args) {
//        SwingUtilities.invokeLater(() -> {
//            deleteFlightView deleteFlightForm = new deleteFlightView();
//            deleteFlightForm.setSize(300, 100);
//            deleteFlightForm.setVisible(true);
//        });
    }
}
